import React, { PureComponent } from "react";

export class App extends PureComponent {
  constructor() {
    super()

    this.state = {
      isAgree: false,
      hobbies: [
        { value: 'sing', text: '唱', isChecked: false },
        { value: 'play', text: '打游戏', isChecked: false },
        { value: 'movie', text: '看电影', isChecked: false }
      ]
    }
  }

  handleClick(e) {
    e.preventDefault()
    const hobbies = this.state.hobbies.filter(item => item.isChecked).map(item => item.text)
    console.log('是否同意协议:',this.state.isAgree,'爱好：',hobbies);
  }
  
  // 单选
  handleCheckBoxChange(e) {
    // checkbox或者radio取的是checked的值
    console.log(e.target.checked);
    this.setState({
      isAgree: e.target.checked
    })
  }

  // 多选
  handleMultiCheck(e, index) {
    const hobbies = [...this.state.hobbies]
    hobbies[index].isChecked = e.target.checked
    this.setState({ hobbies })
  }
  render() {

    const { isAgree, hobbies } = this.state
    return (
      <div>
        <form onSubmit={(e) => this.handleClick(e)}>
          <div>
            {/* checkbox单选 */}
            <label htmlFor="agree">
              <input 
                type="checkbox" 
                id="agree" 
                checked={isAgree} 
                onChange={(e) => this.handleCheckBoxChange(e)}
              /> 同意协议
            </label>
          </div>
          <div>
            选择爱好:
            {/* checkbox多选 */}
            {
              hobbies.map((item, index) => {
                return (
                  <label htmlFor={item.value} key={item.value}>
                    <input 
                      type="checkbox" 
                      id={item.value}  
                      checked={item.isChecked}
                      onChange={(e) => this.handleMultiCheck(e, index)}
                    />
                    {item.text}
                  </label>
                )
              })
            }
          </div>
          <button type="submit">注册</button>
        </form>
      </div>
    )
  }
}

export default App;
